package com.study.book.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.study.book.common.AuthenticationRequired;
import com.study.book.common.R;
import com.study.book.pojo.Collect;
import com.study.book.pojo.Library;
import com.study.book.service.CollectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 陈坤
 * @version 1.0.0
 * @description TODO
 * @date 2024-05-05 23:09
 */
@Api(tags = "用户收藏图书馆接口")
@RestController
@RequestMapping("/app/collect")
public class CollectController {

    @Autowired
    private CollectService collectService;


    @ApiOperation("获取收藏图书馆数据")
    @GetMapping("/list")
    @AuthenticationRequired("0")
    public R<List<Library>> list(HttpServletRequest request) {
        String id = (String) request.getAttribute("userId");
        return collectService.listCollect(id);
    }

    @ApiOperation("确认是否收藏图书馆")
    @GetMapping("/check/{libraryId}")
    @AuthenticationRequired("0")
    public R check(HttpServletRequest request,@PathVariable("libraryId") Integer libraryId) {
        String id = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Collect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Collect::getLibraryid,libraryId).eq(Collect::getAdminid,id);
        List<Collect> list = collectService.list(lambdaQueryWrapper);
        if (list.size()==0)return R.ok('0');
        else return R.ok('1');
    }

    @ApiOperation("添加收藏图书馆")
    @GetMapping("/add/{libraryId}")
    @AuthenticationRequired("0")
    public R add(HttpServletRequest request,@PathVariable("libraryId") Long libraryId) {
        String id = (String) request.getAttribute("userId");
        Collect collect=new Collect();
        collect.setAdminid(Integer.valueOf(id)).setLibraryid(Math.toIntExact(libraryId));
        collectService.saveOrUpdate(collect);
        return R.ok();
    }

    @ApiOperation("删除收藏图书馆")
    @GetMapping("/del/{libraryId}")
    @AuthenticationRequired("0")
    public R del(HttpServletRequest request,@PathVariable("libraryId") Long libraryId) {
        String id = (String) request.getAttribute("userId");
        LambdaQueryWrapper<Collect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Collect::getLibraryid,libraryId).eq(Collect::getAdminid,id);
        collectService.remove(lambdaQueryWrapper);
        return R.ok();
    }
}
